<template>
  <a-card>
    <template #title>
      <a-form layout="vertical">
        <a-row :gutter="16">
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('商户名称')">
              <a-input v-model:value="page.name"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('商户号')">
              <a-input v-model:value="page.no"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('商户账号')">
              <a-input v-model:value="page.account"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('状态')">
              <a-select v-model:value="page.status">
                <a-select-option :value="1">{{ $t('启用') }}</a-select-option>
                <a-select-option :value="0">{{ $t('禁用') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col style="text-align: right" :span="24">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">{{ $t('重置') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <div style="text-align: right;margin-bottom: 10px">
      <a-button type="primary" @click="addMerchant">{{ $t('添加商户') }}</a-button>
    </div>
    <a-table :columns="tableColumn" :loading="tableLoading" :pagination="pagination" :scroll="{x:true,y:600}"
             row-key="id"
             :data-source="tableData">
      <template #status="{record }">
        <a-switch :checked="record.status === 1" @change="changeStatus(record)"></a-switch>
      </template>
      <template #operation="{record }">
        <a-button type="link" @click="editMerchant(record)">{{ $t('编辑') }}</a-button>
        <a-button type="link" @click="merchantConfig(record)">{{ $t('商户设置') }}</a-button>
        <a-button type="link" @click="setPeriod(record)">{{ $t('综合设置') }}</a-button>
        <a-button type="link" @click="forgetLoginPwd(record)">{{ $t('忘记登录密码') }}</a-button>
        <a-button type="link" @click="forgetTransactionPwd(record)">{{ $t('忘记交易密码') }}</a-button>
        <a-button type="link" @click="bindGoogleSecret(record)">{{ $t('重绑谷歌验证器') }}</a-button>
      </template>
    </a-table>
    <!--综合设置-->
    <a-modal v-model:visible="visiblePeriod" :title="periodForm.name + '-' + $t('综合设置')" @ok="periodConfirm"
             width="50%">
      <div style="margin-bottom: 15px">
        <div class="config_title">{{ $t('结算周期设置') }}</div>
        <div style="margin-top: 10px">
          <a-radio-group v-model:value="periodForm.settlement_period">
            <a-radio v-for="item in periodList" :value="item.key">{{ item.value }}</a-radio>
          </a-radio-group>
        </div>
      </div>
      <div class="config_title">{{ $t('商户打款/提现设置') }}</div>
      <div style="margin-top: 10px">
        <a-form layout="vertical">
          <a-row :gutter="16">
            <a-col :md="12" :xs="24">
              <a-form-item :label="$t('每日打款总额上限')">
                <a-input v-model:value="periodForm.day_payment_max_amount"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :xs="24">
              <a-form-item :label="$t('每日同一收款账号打款总额上限')">
                <a-input v-model:value="periodForm.day_same_clabe_payment_max_amount"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :xs="24">
              <a-form-item :label="$t('每日同一收款账号打款次数上限')">
                <a-input v-model:value="periodForm.day_same_clabe_payment_max_num"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :xs="24">
              <a-form-item :label="$t('每日提现总额上限')">
                <a-input v-model:value="periodForm.day_withdrawal_max_amount"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :xs="24">
              <a-form-item :label="$t('每日同一收款账号提现总额上限')">
                <a-input v-model:value="periodForm.day_same_clabe_withdrawal_max_amount"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :xs="24">
              <a-form-item :label="$t('每日同一收款账号提现次数上限')">
                <a-input v-model:value="periodForm.day_same_clabe_withdrawal_max_num"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

    </a-modal>
    <!--    添加商户-->
    <a-modal v-model:visible="visibleMerchant.isShow" :title="visibleMerchant.title" @ok="merchantConfirm"
             :confirm-loading="confirmLoading"
             :after-close="clearMerchantForm">
      <a-form ref="merchantRef" :model="merchantForm" :rules="merchantFormRules"
              :label-col="{span:4}"
              label-align="left">
        <a-form-item name="name" :label="$t('商户名称')">
          <a-input v-model:value="merchantForm.name" :disabled="visibleMerchant.type === 'edit'"
                   :placeholder="$t('只能输入字母数字')"/>
        </a-form-item>
        <a-form-item name="account" :label="$t('商户账号')">
          <a-input v-model:value="merchantForm.account" :disabled="visibleMerchant.type === 'edit'"
                   :placeholder="$t('只能输入字母数字')"/>
        </a-form-item>
        <a-form-item :label="$t('联系电话')">
          <a-input v-model:value="merchantForm.phone"/>
        </a-form-item>
        <a-form-item name="email" :label="$t('邮箱')">
          <a-input v-model:value="merchantForm.email" :disabled="visibleMerchant.type === 'edit'"/>
        </a-form-item>
        <a-form-item name="password" :label="$t('密码')" v-if="visibleMerchant.type === 'add'">
          <a-input v-model:value="merchantForm.password"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import {onMounted, reactive, toRefs, ref, computed, h} from 'vue'
import i18n from "../../../locale";
import {
  fetchMerchantList,
  settlementPeriod,
  increaseMerchant,
  updateMerchant,
  sendResetLoginPwdEmail,
  sendResetTransPwdEmail,
  updateStatus,
  fetchConfig,
  updateConfig
} from '@/api/merchant'
import {message, Modal} from "ant-design-vue";
import router from "../../../router";
import {getResetGoogleSecretLink} from "../../../api";

const $t = i18n.global.t
const periodList = [
  {value: 'D+0', key: 0},
  {value: 'D+1', key: 1},
  {value: 'D+2', key: 2},
  {value: 'D+3', key: 3},
]
const tableColumn = [
  {
    title: $t('商户名称'),
    dataIndex: 'name',
    width: 100,
    align: 'center'
  },
  {
    title: $t('商户号'),
    dataIndex: 'no',
    width: 100,
    align: 'center'
  },
  {
    title: $t('商户账号'),
    dataIndex: 'account',
    width: 100,
    align: 'center'
  },
  {
    title: $t('联系电话'),
    dataIndex: 'phone',
    width: 100,
    align: 'center'
  },
  {
    title: $t('邮箱'),
    dataIndex: 'email',
    width: 150,
    align: 'center'
  },
  {
    title: $t('结算周期'),
    dataIndex: 'returnType',
    width: 100,
    align: 'center',
    customRender: ({text}) => {
      const value = periodList.find(item => item.key === text)
      if (value) {
        return value.value
      }
    }
  },
  {
    title: $t('创建时间'),
    dataIndex: 'creationTime',
    width: 150,
    align: 'center'
  },
  {
    title: $t('状态'),
    dataIndex: 'status',
    width: 150,
    align: 'center',
    slots: {
      customRender: 'status',
    },
  },
  {
    title: $t('操作'),
    align: 'center',
    fixed: 'right',
    width: 250,
    slots: {
      customRender: 'operation',
    },
  },
]
export default {
  name: "MerchantList",
  setup() {
    const merchantRef = ref(null)
    const validatorNumber = (rule, value) => {
      if (!value) {
        return Promise.reject($t('不能为空'))
      } else if (value && !/^[a-z0-9]+$/i.test(value)) {
        return Promise.reject($t('只能输入字母数字'))
      }
      return Promise.resolve()
    }
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      tableLoading: false,
      visiblePeriod: false,
      periodForm: {},
      visibleMerchant: {
        isShow: false,
        title: '',
        type: ''
      },
      merchantForm: {},
      merchantFormRules: {
        name: [
          {
            required: true, validator: validatorNumber, trigger: 'blur'
          }
        ],
        account: [
          {
            required: true, validator: validatorNumber, trigger: 'blur'
          }
        ],
        password: {required: true, message: $t('不能为空'), trigger: 'blur'},
        email: [
          {required: true, message: $t('不能为空'), trigger: 'blur'},
          {
            required: true, trigger: 'blur', validator: (rule, value) => {
              if (value && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
                return Promise.reject($t('邮箱格式错误'))
              }
              return Promise.resolve()
            },
          }
        ],
      },
      confirmLoading:false
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + $t('条'),
      onChange: (value) => {
        state.page.pageNum = value
        methods.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        methods.getTableData()
      }
    }))
    const methods = {
      async getTableData() {
        state.tableLoading = true
        const res = await fetchMerchantList(state.page)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
          state.tableLoading = false
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        methods.getTableData()
      },
      changeStatus({id, status}) {
        Modal.confirm({
          title: $t('确认进行此操作') + '?',
          async onOk() {
            const res = await updateStatus({id, status: status === 1 ? 0 : 1})
            if (res.code === 200) {
              message.success($t('操作成功'))
              methods.getTableData()
            }
          },
        });
      },
      setPeriod(row) {
        fetchConfig({
          mchId: row.id
        }).then(res => {
          if (res.code === 200) {
            const keysValue = {}
            res.data.forEach(item => {
              if (item.key) {
                keysValue[item.key] = item.value
              }
            })
            state.periodForm = {
              ...keysValue,
              settlement_period: parseInt(keysValue.settlement_period),
              mchId: row.id,
              name: row.name,
            }
            state.visiblePeriod = true
          }

        })
      },
      addMerchant() {
        state.visibleMerchant = {
          isShow: true,
          title: $t('添加'),
          type: 'add'
        }
      },
      async merchantConfirm() {
        merchantRef.value.validate().then(async () => {
          state.confirmLoading = true
          const api = ((params) => state.visibleMerchant.type === 'add' ? increaseMerchant(params) : updateMerchant(params))
          const res = await api({...state.merchantForm, systemUserId: state.merchantForm.id})
          if (res.code === 200) {
            state.visibleMerchant.isShow = false
            message.success(state.visibleMerchant.type === 'add' ? $t('添加成功') : $t('编辑成功'))
            methods.getTableData()
          }
          state.confirmLoading = false
        })
      },
      clearMerchantForm() {
        state.merchantForm = {}
        merchantRef.value.resetFields()
      },
      editMerchant(row) {
        state.visibleMerchant = {
          isShow: true,
          title: $t('编辑'),
          type: 'edit'
        }
        state.merchantForm = {...row}
      },
      async forgetTransactionPwd({name, id}) {
        Modal.confirm({
          title: $t('提示'),
          content: $t(`请确认是否向发送重置交易密码的邮件?`, {name: name,}),
          async onOk() {
            const res = await sendResetTransPwdEmail({mchId: id})
            if (res.code === 200) {
              message.success($t('发送成功'))
            }
          },
        });
      },
      forgetLoginPwd({name, id}) {
        Modal.confirm({
          title: $t('提示'),
          content: $t(`请确认是否向发送重置登录密码的邮件?`, {name: name,}),
          async onOk() {
            const res = await sendResetLoginPwdEmail({mchId: id})
            if (res.code === 200) {
              message.success($t('发送成功'))
            }
          },
        });
      },
      merchantConfig(row) {
        const {id} = row
        router.push({
          path: '/merchant/merchantInfo',
          query: {
            id
          }
        })
      },
      async periodConfirm() {
        const paramsList = Object.keys(state.periodForm).map(key => {
          return {
            key: key,
            value: state.periodForm[key],
            mchId: state.periodForm.mchId
          }
        }).filter(item => item.key !== 'name' && item.key !== 'mchId')
        console.log(paramsList)
        const res = await updateConfig(paramsList)
        if (res.code === 200) {
          message.success($t('操作成功'))
          methods.getTableData()
          state.visiblePeriod = false
        }
      },
      async bindGoogleSecret(row) {
        const res = await getResetGoogleSecretLink({adminUserId: row.id})
        if (res.code === 200) {
          Modal.confirm({
            okText: '复制链接',
            content: h('div', {
              style: {
                fontSize: '14px'
              }
            }, '重绑链接:', h('span', {
              style: {
                color: '#1890ff',
              },
            }, res.data)),
            onOk: () => {
              let input = document.createElement("input");
              input.value = res.data || ''
              document.body.appendChild(input);
              input.select()
              document.execCommand('copy')
              message.success($t('复制成功'))
              document.body.removeChild(input);
            }
          });
        }

      }
    }
    onMounted(() => {
      methods.getTableData()
    })
    return {
      merchantRef,
      periodList,
      tableColumn,
      pagination,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>
.config_title {
  height: 40px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 18px;
  font-weight: bold;
}
</style>
